package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import com.qiniu.sms.SmsManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("validateCode")
public class validateCodeController {


    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("send2telephone")
    public Result send2telephone(@RequestParam("telephone") String telephone) {
        try {
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);

            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode.toString());

            String key = telephone + RedisMessageConstant.SENDTYPE_ORDER;

            jedisPool.getResource().setex(key, 600, validateCode.toString());

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("send2Login")
    public Result send2Login(@RequestParam("telephone") String telephone) {
        try {
            Integer code = ValidateCodeUtils.generateValidateCode(4);

            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());

            String key = telephone + RedisMessageConstant.SENDTYPE_LOGIN;
            jedisPool.getResource().setex(key, 600, code.toString());

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
